package com.wry.myphotowall.adapter;

import android.content.Context;
import android.graphics.PointF;
import android.net.Uri;
import android.support.v4.view.PagerAdapter;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.wry.myphotowall.R;
import com.wry.myphotowall.listener.OnPagerCLickListener;
import com.wry.myphotowall.zoomable.AbstractAnimatedZoomableController;
import com.wry.myphotowall.zoomable.DefaultZoomableController;
import com.wry.myphotowall.zoomable.ZoomableDraweeView;

import java.util.ArrayList;

public class PhotoPagerAdapter extends PagerAdapter {

    private Context mContext;
    private ArrayList<String> mPaths;
    private OnPagerCLickListener mOnPagerCLickListener;


    private final PointF mDoubleTapViewPoint = new PointF();
    private final PointF mDoubleTapImagePoint = new PointF();
    private float mDoubleTapScale = 1;
    private boolean mDoubleTapScroll = false;
    private static final int DURATION_MS = 300;
    private static final int DOUBLE_TAP_SCROLL_THRESHOLD = 20;


    public void setOnPagerCLickListener(OnPagerCLickListener onPagerCLickListener) {
        mOnPagerCLickListener = onPagerCLickListener;
    }

    public PhotoPagerAdapter(Context context, ArrayList<String> paths) {
        mContext = context;
        mPaths = paths;
    }

    @Override
    public int getCount() {
        return mPaths != null ? mPaths.size() : 0;
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_pager, null);
        final ZoomableDraweeView zoomableDraweeView = (ZoomableDraweeView) view.findViewById(R.id.iv_pager);
        //允许缩放时切换
        zoomableDraweeView.setAllowTouchInterceptionWhileZoomed(true);
        //长按
        zoomableDraweeView.setIsLongpressEnabled(false);
        zoomableDraweeView.setTapListener(new GestureDetector.SimpleOnGestureListener() {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                mOnPagerCLickListener.onPagerClick();
                return true;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                //双击击放大或缩小
                AbstractAnimatedZoomableController zc =
                        (AbstractAnimatedZoomableController) zoomableDraweeView.getZoomableController();
                PointF vp = new PointF(e.getX(), e.getY());
                PointF ip = zc.mapViewToImage(vp);
                switch (e.getActionMasked()) {
                    case MotionEvent.ACTION_DOWN:
                        mDoubleTapViewPoint.set(vp);
                        mDoubleTapImagePoint.set(ip);
                        mDoubleTapScale = zc.getScaleFactor();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mDoubleTapScroll = mDoubleTapScroll || shouldStartDoubleTapScroll(vp);
                        if (mDoubleTapScroll) {
                            float scale = calcScale(vp);
                            zc.zoomToPoint(scale, mDoubleTapImagePoint, mDoubleTapViewPoint);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (mDoubleTapScroll) {
                            float scale = calcScale(vp);
                            zc.zoomToPoint(scale, mDoubleTapImagePoint, mDoubleTapViewPoint);
                        } else {
                            final float maxScale = zc.getMaxScaleFactor();
                            final float minScale = zc.getMinScaleFactor();
                            if (zc.getScaleFactor() < (maxScale + minScale) / 2) {
                                zc.zoomToPoint(
                                        maxScale,
                                        ip,
                                        vp,
                                        DefaultZoomableController.LIMIT_ALL,
                                        DURATION_MS,
                                        null);
                            } else {
                                zc.zoomToPoint(
                                        minScale,
                                        ip,
                                        vp,
                                        DefaultZoomableController.LIMIT_ALL,
                                        DURATION_MS,
                                        null);
                            }
                        }
                        mDoubleTapScroll = false;
                        break;
                }
                return false;
            }
        });
        DraweeController draweeController;
        if (mPaths.get(position).startsWith("http://") || mPaths.get(position).startsWith("https://")) {
            draweeController = Fresco.newDraweeControllerBuilder()
                    .setUri(Uri.parse(mPaths.get(position)))
                    .build();
        } else {
            draweeController = Fresco.newDraweeControllerBuilder()
                    .setUri(Uri.parse("file://" + mPaths.get(position)))
                    .build();
        }
        //加载图片
        zoomableDraweeView.setController(draweeController);
        container.addView(view);
        view.requestLayout();
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;

        ZoomableDraweeView zoomableDraweeView = (ZoomableDraweeView) view.findViewById(R.id.iv_pager);
        zoomableDraweeView.setController(null);
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        if (mPaths.get(position).startsWith("http://") || mPaths.get(position).startsWith("https://")) {

        } else {
            imagePipeline.clearCaches();
        }
        container.removeView(view);
    }

    private boolean shouldStartDoubleTapScroll(PointF viewPoint) {
        double dist = Math.hypot(
                viewPoint.x - mDoubleTapViewPoint.x,
                viewPoint.y - mDoubleTapViewPoint.y);
        return dist > DOUBLE_TAP_SCROLL_THRESHOLD;
    }

    private float calcScale(PointF currentViewPoint) {
        float dy = (currentViewPoint.y - mDoubleTapViewPoint.y);
        float t = 1 + Math.abs(dy) * 0.001f;
        return (dy < 0) ? mDoubleTapScale / t : mDoubleTapScale * t;
    }
}